CLI 开发完成:调试生成 template 代码
概述
本节完成 CLI 工具的最后部分:EJS 模板渲染和调试。解决 base 目录遍历缺失的问题,完善文件处理逻辑,并对 configPage 参数进行精确的类型判断。
EJS 模板渲染
处理 .ejs 文件
import ejs from 'ejs'
import fs from 'fs-extra'
import path from 'path'
async function processFile(currentPath: string, destPath: string, options: any) {
if (currentPath.endsWith('.ejs')) {
// 读取 EJS 模板
const template = await fs.readFile(currentPath, 'utf-8')
// 使用 options 渲染模板
const result = ejs.render(template, options)
// 输出文件去掉 .ejs 后缀
const outputPath = destPath.replace('.ejs', '')
await fs.ensureDir(path.dirname(outputPath))
await fs.writeFile(outputPath, result)
} else {
// 非 EJS 文件直接复制
await fs.ensureDir(path.dirname(destPath))
await fs.copy(currentPath, destPath)
}
}
typescript
修复 base 目录遍历
问题定位
用户传递的 options.configPage 是一个数组,原代码未单独处理 base 基础目录,导致基础模板文件未被复制。
修正代码
// 精确判断 configPage 类型
if (configPage instanceof Array) {
// 1. 始终处理 base 基础目录
const basePath = path.join(templatesDir, 'base')
if (await fs.pathExists(basePath)) {
await workFiles(basePath, { ...options, dest: outputDir })
}
// 2. 遍历用户选择的配置
for (const config of configPage) {
// 处理每个配置项...
}
}
typescript
调试技巧
VS Code 断点调试
- 在关键行设置断点(如第 148 行)
- 配置
launch.json:
{
"type": "node",
"request": "launch",
"name": "Debug CLI",
"program": "${workspaceFolder}/bin/create-vp.js",
"args": ["test-project"]
}
json
- 按 F5 启动调试,在断点处检查变量值
调试检查清单
| 检查项 | 验证方法 |
|---|---|
| configPage 类型 | console.log(typeof configPage, configPage) |
| base 目录路径 | console.log(basePath, fs.existsSync(basePath)) |
| EJS 渲染结果 | console.log(result.substring(0, 100)) |
| 输出路径 | console.log(outputPath) |
后续优化方向
1. 输入校验
// 校验失败时给出友好提示
function validateInput(input: string): boolean {
if (!input.trim()) {
console.log('项目名称不能为空')
return false
}
return true
}
typescript
2. 目录覆盖确认
// 检查目标目录是否已存在
if (await fs.pathExists(targetDir)) {
const { overwrite } = await prompts({
type: 'confirm',
name: 'overwrite',
message: '目标目录已存在,是否覆盖?',
})
if (!overwrite) process.exit(0)
}
typescript
关键要点
- EJS 模板文件使用
ejs.render(template, options)渲染,输出时去掉.ejs后缀 - base 目录是默认必须处理的基础模板,需在遍历 configPage 之前单独处理
- 使用
instanceof Array精确判断 configPage 类型 - 通过 VS Code 断点调试快速定位问题
- 后续可扩展输入校验和目录覆盖确认功能
↑